#
from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers
from goods.models import SKU
from goods.search_indexes import SUKSKUIndex
from goods.utils import PageNum
from django_redis import get_redis_connection


class SKUSSerialziers(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUIndexSerializer(HaystackSerializer):
    """
    SKU索引结果数据序列化器
    """
    object = SKUSSerialziers(read_only=True)

    class Meta:
        index_classes = [SUKSKUIndex]
        fields = ('text', 'object')
        pagination_class = PageNum


class SKUHistorySerialzier(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        # 判断商品是否存在
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        # 获取商品id
        sku_id = validated_data['sku_id']
        conn = get_redis_connection('history')
        # 判断当前id是否存在缓存中
        # 建立管道
        pl = conn.pipeline()
        pl.lrem('history_%s' % user.id, 0, sku_id)
        pl.lpush('history_%s' % user.id, sku_id)
        pl.ltrim('history_%s' % user.id, 0, 4)
        pl.execute()
        return validated_data
